	package controller;

import java.io.File;

import net.sf.jasperreports.engine.JRDataSource;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileUpload;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.mindrot.jbcrypt.BCrypt;

import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import pojo.Brand;
import pojo.Comment;
import pojo.Condition;
import pojo.Deals;
import pojo.Orders;
import pojo.Orderstatus;
import pojo.Orderdetail;
import pojo.Productcatalog;
import pojo.Products;
import pojo.User;
import pojo.Userroles;
import dao.AdminDAO;
import pojo.Wishlist;
import dao.BrandDAO;
import dao.CommentDAO;
import dao.ConditionDAO;
import dao.DealsDAO;
import dao.OrderDetailDAO;
import dao.OrderStatusDAO;
import dao.OrdersDAO;
import dao.ProductCatalogDAO;
import dao.ProductsDAO;
import dao.UserDAO;
import dao.WishListDAO;

@Controller
public class Index {

	@Autowired
	private UserDAO userDAO;
	@Autowired
	private ProductsDAO productDAO;
	@Autowired
	private ProductCatalogDAO productCatalogDAO;
	@Autowired
	private BrandDAO brandDAO;
	@Autowired
	private ConditionDAO conditionDAO;
	@Autowired
	private DealsDAO dealsDAO;
	@Autowired
	private AdminDAO adminDAO;
	@Autowired
	private WishListDAO wishListDAO;
	@Autowired
	private CommentDAO commentDAO;
	@Autowired
	private OrdersDAO ordersDAO;
	@Autowired
	private OrderDetailDAO orderDetailDAO;
	@Autowired
	private OrderStatusDAO orderStatusDAO;

	RequestDispatcher rd;

	HttpSession session;
	String url;
	private static final Logger logger = Logger.getLogger(Index.class);
	@RequestMapping(value = { "/Homepage.do", "/" }, method = RequestMethod.GET)
	public String doAppliance(Model model) {
		logger.info("-----------------------Load homepage------------------");
		
		logger.info("Done Load homepage");
		return "Homepage";
		
	}

	@RequestMapping(value = { "/LoadSignin.do" }, method = RequestMethod.GET)
	public String doLoadSignin(Model model) {
		 
		logger.info("Login");
		return "SignIn";
	}
	@RequestMapping(value = { "/About.do" }, method = RequestMethod.GET)
	public String doAbout(Model model) {
		 
		return "About";
	}


	@RequestMapping(value = { "/LoadRegister.do" }, method = RequestMethod.GET)
	public String doLoadRegister(Model model) {
		 
		
		return "Register";
	}

	@RequestMapping(value = { "/Register.do" }, method = RequestMethod.POST)
	public String doRegister(Model model, HttpServletRequest request,
			HttpServletResponse response) throws NoSuchAlgorithmException {
		
		logger.info("Load register");
		 
		String firstname;
		String lastname;
		String email1;
		String emailreenter;
		String password1;
		String passwordreenter;
		String zipcode = "";
		String phonenumber = "";
		String password2;
		firstname = request.getParameter("firstname");
		lastname = request.getParameter("lastname");
		email1 = request.getParameter("email");
		password1 = request.getParameter("password");
		//encrypt md5
		MessageDigest messageDigest = MessageDigest.getInstance("MD5");  
		messageDigest.update(password1.getBytes(),0, password1.length());  
		String hashedPass = new BigInteger(1,messageDigest.digest()).toString(16);  
		if (hashedPass.length() < 32) {
		   hashedPass = "0" + hashedPass; 
		}
		
		
		emailreenter = request.getParameter("reenteremail");
		passwordreenter = request.getParameter("reenterpassword");
		if (request.getParameter("zipcode") != null) {
			zipcode = request.getParameter("zipcode");
		}
		if (request.getParameter("phonenumber") != null) {
			phonenumber = request.getParameter("phonenumber");
		}
		boolean returnResult1 = true;
		if (request.getParameter("email") != ""
				&& request.getParameter("password") != ""
				&& request.getParameter("reenteremail") != ""
				&& request.getParameter("reenterpassword") != "") {
			
			if (email1.equals(emailreenter)
					&& password1.equals(passwordreenter)) {
				if (userDAO.checkRegisterEmail(email1) == true) {
					request.setAttribute("returnResult", returnResult1);
					request.setAttribute("firstname", firstname);
					request.setAttribute("lastname", lastname);
					request.setAttribute("zipcode", zipcode);
					request.setAttribute("phonenumber", phonenumber);
					request.setAttribute("returnResult", false);
					return "Register";
				}
				

				User user = new User(firstname, lastname, email1, hashedPass,
						phonenumber, zipcode);
				returnResult1 = userDAO.addUser(user);
				if (returnResult1 == true) {
					return "SignIn";
				} else {
					request.setAttribute("returnResult", returnResult1);
					request.setAttribute("firstname", firstname);
					request.setAttribute("lastname", lastname);
					request.setAttribute("email1", email1);
					request.setAttribute("zipcode", zipcode);
					request.setAttribute("phonenumber", phonenumber);
					return "Register";

				}
			} else {
				request.setAttribute("returnResult", returnResult1);
				request.setAttribute("firstname", firstname);
				request.setAttribute("lastname", lastname);
				request.setAttribute("email1", email1);
				request.setAttribute("zipcode", zipcode);
				request.setAttribute("phonenumber", phonenumber);
				request.setAttribute("emailandpassword",
						"Please write correct E-mail and password");

			}

		} else {
			request.setAttribute("fullinfo",
					"Please fill in blanks in this form!");
		}
		logger.info("Done load register");
		return "Register";
	}

	@RequestMapping(value = { "/Search.do" }, method = RequestMethod.GET)
	public String doSearch(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("Load Search page");
		 
		String productname = "";
		if (request.getParameter("productname") != null) {
			productname = request.getParameter("productname");
		}
		String productcatalog = "-1";
		if (request.getParameter("productcatalog") != null) {
			productcatalog = request.getParameter("productcatalog");
		}

		String[] brands = request.getParameterValues("brand");

		String[] conditions = request.getParameterValues("condition");
		String rating = "-1";
		if (request.getParameter("rating") != null) {
			rating = request.getParameter("rating");
		}
		String minprice = "";
		if (request.getParameter("minprice") != null) {
			minprice = request.getParameter("minprice");
		}

		String maxprice = "";
		if (request.getParameter("maxprice") != null) {
			maxprice = request.getParameter("maxprice");
		}

		int productonpage = 2;
		if (request.getParameter("productonpage") != null) {
			productonpage = Integer.valueOf(request
					.getParameter("productonpage"));
		}

		int page = 1;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}

		int sortby = -1;
		if (request.getParameter("sortby") != null) {
			sortby = Integer.parseInt(request.getParameter("sortby"));
		}

		int pagecount = productCatalogDAO.pagecount(productname,
				productcatalog, brands, conditions, rating, productonpage,
				minprice, maxprice);
		List<Products> listproduct = productDAO.Search(productname,
				productcatalog, brands, conditions, rating, minprice, maxprice,
				page, productonpage, sortby);
		request.setAttribute("productname", productname);
		request.setAttribute("productcatalog", productcatalog);
		request.setAttribute("rating", rating);
		request.setAttribute("page", page);
		request.setAttribute("listbrand", brands);
		request.setAttribute("listcondition", conditions);
		request.setAttribute("minprice", minprice);
		request.setAttribute("maxprice", maxprice);
		request.setAttribute("productonpage", productonpage);
		request.setAttribute("pagecount", pagecount);
		request.setAttribute("listproduct", listproduct);
		request.setAttribute("sortby", sortby);
		request.setAttribute("listsortby", listsortby);
		logger.info("Done load search page");
		return "Search";

	}

	ArrayList<String> listsortby = new ArrayList<String>() {
		{
			add("Z-A");
			add("Price low to high");
			add("Price high to low");
			add("highest rating");
		}
	};

	@RequestMapping(value = { "/Products.do" }, method = RequestMethod.GET)
	public String doProducts(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("Load products");
		 
		String catalogid;
		if (request.getParameter("catalogid") != null) {
			catalogid = request.getParameter("catalogid");
		} else {
			catalogid = "1";
		}
		Productcatalog productcatalog = productCatalogDAO
				.getProductCatalog(catalogid);
		doProductsBuff(request,response, catalogid, "catalog");
		
		request.setAttribute("productcatalog", productcatalog);
		logger.info("Done load product");
		return "ListProduct";
	}
	
	

	@RequestMapping(value = { "/ProductsBrand.do" }, method = RequestMethod.GET)
	public String doProductsBrand(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("Load products by brand");
		 
		String brandid;
		if (request.getParameter("brandid") != null) {
			brandid = request.getParameter("brandid");
		} else {
			brandid = "1";
		}
		Brand brand = brandDAO.getBrand(brandid);
		
		doProductsBuff(request,response, brandid, "brand");
		request.setAttribute("brand", brand);
		
		logger.info("Done load product by brand");
		return "ListProductByBrand";
	}

	private void doProductsBuff(HttpServletRequest request,
			HttpServletResponse response, String id, String type) {
		// TODO Auto-generated method stub
		int productonpage = 2;
		if (request.getParameter("productonpage") != null) {
			productonpage = Integer.parseInt(request
					.getParameter("productonpage"));
		}
		int page = 1;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}

		int sortby = -1;
		if (request.getParameter("sortby") != null) {
			sortby = Integer.parseInt(request.getParameter("sortby"));
		}

		int pagecount = productDAO.pagecount(id, productonpage, type);
		List<Products> listproduct = productDAO.getProductList(id,
				productonpage, page, sortby, type);
		
		request.setAttribute("productonpage", productonpage);
		request.setAttribute("page", page);
		request.setAttribute("pagecount", pagecount);
		request.setAttribute("sortby", sortby);
		request.setAttribute("listsortby", listsortby);
		request.setAttribute("listproduct", listproduct);
		
	}

	@RequestMapping(value = { "/Manage.do" }, method = RequestMethod.GET)
	public String doManage(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		 
		return "redirect:/Users.do";
	}

	@RequestMapping(value = { "/Signinadmin.do" }, method = RequestMethod.GET)
	public String dosigninadmin(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		 
		return "SignIn";
	}
	@RequestMapping(value = { "/Signingoogle.do" }, method = RequestMethod.GET)
	public String dosigningoogle(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		 
		return "SignInGoogle";
	}

	//
	// @RequestMapping(value={"/Signinadminsuccess"},method = RequestMethod.GET)
	// public String dosigninadminsuccess(Model model, HttpServletRequest
	// request)
	// {
	//
	// }
	@RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
	public String loginerror(Model model) {
		logger.info("Login fail");
		 
		model.addAttribute("error", "true");
		return "SignIn";

	}

	// deals manage
	@RequestMapping(value = { "/Deals.do" }, method = RequestMethod.GET)
	public String doDeals(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		List<Deals> deals = adminDAO.getdeallist();
		request.setAttribute("deallist", deals);
		return "DealsManage";
	}

	@RequestMapping(value = { "/EditDealsJsp.do" }, method = RequestMethod.GET)
	public String doEditDealsjsp(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		String dealidstr = request.getParameter("dealid");
		int dealid = Integer.parseInt(dealidstr);
		Deals deal = adminDAO.getdealbyid(dealid);
		request.setAttribute("dealid", dealid);
		request.setAttribute("dealname", deal.getDealname());
		request.setAttribute("dealimage", deal.getDealimage());
		request.setAttribute("dealdescription", deal.getDealdescription());
		return "EditDeals";
	}

	@RequestMapping(value = { "/EditDeals.do" }, method = RequestMethod.POST)
	public String doEditDeals(@RequestParam(value = "file") MultipartFile file,
			Model model, HttpServletRequest request,
			HttpServletResponse response) throws URISyntaxException {
		logger.info("Load Edit deals");
		String dealidstr = request.getParameter("dealid");
		int dealid = Integer.parseInt(dealidstr);
		String dealname = request.getParameter("dealname");
		String dealimage = request.getParameter("dealimage");
		String filename = file.getOriginalFilename();
		String imageURL = "";

		String filedes = request.getSession().getServletContext()
				.getRealPath("/images/")
				+ "/" + filename;
		File des = new File(filedes);
		if (!des.exists()) {
			try {
				file.transferTo(des);
				
			} catch (Exception e) {
				logger.error("Error when edit deals, this is it :",e);
				e.printStackTrace();
			}
		}
		String dealdescription = request.getParameter("dealdescription");
		if (filename == "") {
			imageURL = dealimage;
		} else
			imageURL = "images/" + filename;
		Deals deal = new Deals(dealid, dealname, imageURL, dealdescription);
		adminDAO.updatedeal(deal);
		List<Deals> deals = adminDAO.getdeallist();
		request.setAttribute("deallist", deals);
		logger.info("Done load edit deal");
		return "DealsManage";
	}

	@RequestMapping(value = { "/CreateDeals.do" }, method = RequestMethod.POST)
	public String doCreateDeals(
			@RequestParam(value = "file") MultipartFile file, Model model,
			HttpServletRequest request, HttpServletResponse response)
			throws URISyntaxException {
		logger.info("Create Deals");
		String dealname = request.getParameter("dealname");
		String filename = file.getOriginalFilename();
		String filedes = request.getSession().getServletContext()
				.getRealPath("/images/")
				+ "/" + filename;
		File des = new File(filedes);
		if (!des.exists()) {
			try {
				file.transferTo(des);
				
			} catch (Exception e) {
				logger.error("Error when create deals, this is it :",e);
				e.printStackTrace();
			}
		}
		String dealdescription = request.getParameter("dealdescription");
		String imageURL = "images/" + filename;
		Deals deal = new Deals(dealname, imageURL, dealdescription);
		adminDAO.adddeal(deal);
		List<Deals> deals = adminDAO.getdeallist();
		request.setAttribute("deallist", deals);

		return "DealsManage";
	}

	@RequestMapping(value = { "/Createdealjsp.do" }, method = RequestMethod.GET)
	public String doCreateDealjsp(Model model, HttpServletRequest request,
			HttpServletResponse response) {

		return "CreateDeals";
	}

	@RequestMapping(value = { "/DeleteDeals.do" }, method = RequestMethod.GET)
	public String doDeleteDeals(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("---------Delete Deals--------");
		int dealid = Integer.parseInt(request.getParameter("dealid"));
		List<Products> prd = adminDAO.getproductlistdealid(dealid);
		for (int i = 0; i < prd.size(); i++) {
			Products p = prd.get(i);
			adminDAO.updateProduct(p.getProductid());

		}

		adminDAO.removedeal(dealid);
		List<Deals> deals = adminDAO.getdeallist();
		request.setAttribute("deallist", deals);
		return "DealsManage";
	}

	// User manage
	@RequestMapping(value = { "/Users.do" }, method = RequestMethod.GET)
	public String doUsers(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		List<User> users = adminDAO.getuserlist();
		request.setAttribute("users", users);
		return "UsersManage";
	}

	//Kiem tra lai
	@RequestMapping(value = { "/DeleteUser.do" }, method = RequestMethod.GET)
	public String doDeleteUser(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("Begin delete user");
		String memberidStr = request.getParameter("memberid");
		int memberid = Integer.parseInt(memberidStr);
		adminDAO.deleterelationuser(memberid);
		User user = adminDAO.getUserbyid(memberid);
		adminDAO.removeUser(user);
		logger.info("Delete User done");
		List<User> users = adminDAO.getuserlist();
		request.setAttribute("users", users);
		return "UsersManage";
	}

	@RequestMapping(value = { "/EditUserJsp.do" }, method = RequestMethod.GET)
	public String doEditUserjsp(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		String memberidStr = request.getParameter("memberid");
		String up = request.getParameter("up");
		Userroles userroles;
		if(up.equals("1"))
		{
			 userroles = adminDAO.getusrolebyrole("ROLE_USER");
		}
		else
			 userroles = adminDAO.getusrolebyrole("ROLE_ADMIN");
		int memberid = Integer.parseInt(memberidStr);
		User user = adminDAO.getUserbyid(memberid);
		user.setUserroles(userroles);
		adminDAO.updateUser(user);
		request.setAttribute("upgrade","upgraded");
		List<User> users = adminDAO.getuserlist();
		request.setAttribute("users", users);
		return "UsersManage";
	}
	@RequestMapping(value = {"/BlockUser.do"},method = RequestMethod.GET)
	public String doblockuser(Model model,HttpServletRequest request)
	{
		logger.info("Begin changing status user");
		String memberidStr = request.getParameter("memberid");
		String enable = request.getParameter("enable");
		int memberid = Integer.parseInt(memberidStr);
		User user = adminDAO.getUserbyid(memberid);		
		if (enable.equals("1"))
		{
			user.setEnable(false);
			logger.info("User Blocked");
		}
		else
		{
			user.setEnable(true);
			logger.info("User Enabled");
		}
		adminDAO.updateUser(user);
		List<User> users = adminDAO.getuserlist();
		request.setAttribute("users", users);
		return "UsersManage";
	}
	@RequestMapping(value = { "/EditUser.do" }, method = RequestMethod.POST)
	public String doEditUser(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("Begin edit user");
		String memberidStr = request.getParameter("memberid");
		String password = request.getParameter("password");
		String firstname = request.getParameter("firstname");
		String lastname = request.getParameter("lastname");
		String email = request.getParameter("email");
		String phonenumber = request.getParameter("phonenumber");
		String zipcode = request.getParameter("zipcode");
		String enableStr = request.getParameter("enable");
		String userrolesStr = request.getParameter("userroles");
		boolean enable;
		int memberid = Integer.parseInt(memberidStr);
		if (enableStr.equals("false"))
			enable = false;
		else
			enable = true;
		Userroles userroles = adminDAO.getusrolebyrole(userrolesStr);
		User user = new User(memberid, firstname, lastname, email, password,
				phonenumber, zipcode, enable, userroles);
		adminDAO.updateUser(user);
		logger.info("Edit user completed");
		List<User> users = adminDAO.getuserlist();
		request.setAttribute("users", users);
		return "UsersManage";

	}

	@RequestMapping(value = { "/DetailsUser.do" }, method = RequestMethod.GET)
	public String dodetailsuser(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		String memberidstr = request.getParameter("memberid");
		int memberid = Integer.parseInt(memberidstr);
		User user = adminDAO.getUserbyid(memberid);
		request.setAttribute("user", user);
		return "DetailsUser";
	}

	// Order Manage
	@RequestMapping(value = { "/Orders.do" }, method = RequestMethod.GET)
	public String doOrders(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		List<Orders> orders = adminDAO.getOrderlist();
		request.setAttribute("orders", orders);
		return "OrdersManage";
	}

	@RequestMapping(value = { "/EditOrderJsp.do" }, method = RequestMethod.GET)
	public String doEditOrderjsp(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		String orderidstr = request.getParameter("orderid");
		int orderid = Integer.parseInt(orderidstr);
		Orders order = adminDAO.getOrderbyid(orderid);
		List<Orderstatus> ostt = adminDAO.getOrderstatusList();
		request.setAttribute("order", order);
		request.setAttribute("liststatus", ostt);
		return "EditOrder";
	}

	@RequestMapping(value = { "DeleteOrder.do" }, method = RequestMethod.GET)
	public String doDeleteOrder(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("Begin delete order");
		String orderidstr = request.getParameter("orderid");
		int orderid = Integer.parseInt(orderidstr);
		adminDAO.deleteorderdetail(orderid);
		Orders order = adminDAO.getorderbyid(orderid);
		adminDAO.removeorder(order);
		logger.info("Delete Order completed");
		List<Orders> orders = adminDAO.getOrderlist();
		request.setAttribute("orders", orders);
		return "OrdersManage";
	}

	@RequestMapping(value = { "/EditOrder.do" }, method = RequestMethod.POST)
	public String doEditOrder(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("Begin edit order");
		String orderidstr = request.getParameter("orderid");
		String orderstatusid = request.getParameter("status");
		int statusid = Integer.parseInt(orderstatusid);
		adminDAO.updatestatus(statusid, Integer.parseInt(orderidstr));
		logger.info("Edit order completed");
		List<Orders> orders = adminDAO.getOrderlist();
		request.setAttribute("orders", orders);
		return "OrdersManage";
	}

	// Products Management
	@RequestMapping(value = { "/ProductsManage.do" }, method = RequestMethod.GET)
	public String doProductmanage(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		
		List<Products> prd = productDAO.getProductList();
		request.setAttribute("products", prd);
		return "ProductManage";

	}

	@RequestMapping(value = { "DeleteProduct.do" }, method = RequestMethod.GET)
	public String dodeleteProduct(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("Begin delete product");
		String productidStr = request.getParameter("productid");
		int productid = Integer.parseInt(productidStr);
		adminDAO.deleterelationproduct(productid);
		adminDAO.removeproductbyid(productid);
		logger.info("Delete product completed");
		List<Products> prd = productDAO.getProductList();
		request.setAttribute("products", prd);
		return "ProductManage";

	}

	@RequestMapping(value = { "EditProductJsp.do" }, method = RequestMethod.GET)
	public String doEditProduct(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		String productid = request.getParameter("productid");
		Products prd = productDAO.getProduct(productid);
		request.setAttribute("product", prd);
		List<Brand> brand = brandDAO.getBrandList();
		List<Deals> deal = dealsDAO.getDealsList();
		List<Condition> condition = conditionDAO.getConditionList();
		List<Productcatalog> cataloglist = productCatalogDAO
				.getProductCatalogList();
		request.setAttribute("brandlist", brand);
		request.setAttribute("deallist", deal);
		request.setAttribute("conditionlist", condition);
		request.setAttribute("cataloglist", cataloglist);
		return "EditProduct";
	}

	@RequestMapping(value = { "/EditProduct.do" }, method = RequestMethod.POST)
	public String doEditProduct(
			@RequestParam(value = "file") List<MultipartFile> file,
			Model model, HttpServletRequest request,
			HttpServletResponse response) throws URISyntaxException {
		logger.info("Begin edit product");
		String productidStr = request.getParameter("productid");
		String productname = request.getParameter("productname");
		String priceStr = request.getParameter("price");
		String model1 = request.getParameter("model");
		String warranty = request.getParameter("warranty");
		String tax = request.getParameter("tax");
		String description = request.getParameter("description");
		String dealid = request.getParameter("deal");
		String productcatalog = request.getParameter("productcatalog");
		String brandid = request.getParameter("brand");
		String specifications = request.getParameter("spec");
		String features = request.getParameter("features");
		String conditionid = request.getParameter("condition");
		String catalogid = request.getParameter("productcatalog");
		String quantity = request.getParameter("quantity");
		String image1 = request.getParameter("image1");
		String image2 = request.getParameter("image2");
		MultipartFile filenamemul = file.get(0);
		MultipartFile filename2mul = file.get(1);
		String filename = filenamemul.getOriginalFilename();
		String filename2 = filename2mul.getOriginalFilename();
		String imageURL1 = "";
		String imageURL2 = "";
		String filedes = request.getSession().getServletContext()
				.getRealPath("/images/")
				+ "/" + filename;
		String filedes2 = request.getSession().getServletContext()
				.getRealPath("/images/")
				+ "/" + filename2;
		File des = new File(filedes);
		File des2 = new File(filedes2);
		if (!des.exists()) {
			try {
				filenamemul.transferTo(des);

			} catch (Exception e) {
				logger.error("Error when tranfer file, this is it :",e);
				e.printStackTrace();
			}
		}
		if (!des2.exists()) {
			try {
				filename2mul.transferTo(des2);
			} catch (Exception e) {
				logger.error("Error when tranfer file, this is it :",e);
				e.printStackTrace();
			}
		}
		if (filename == "") {
			imageURL1 = image1;
		} else
			imageURL1 = "images/" + filename;
		if (filename2 == "") {
			imageURL2 = image2;
		} else
			imageURL2 = "images/" + filename2;
		if (dealid.equals(""))
			dealid = "-1";
		adminDAO.updateProduct(Integer.parseInt(productidStr), productname,
				Float.parseFloat(priceStr), model1, description,
				Integer.parseInt(warranty), imageURL1, imageURL2,
				Float.parseFloat(tax), Integer.parseInt(productcatalog),
				Integer.parseInt(dealid), Integer.parseInt(brandid),
				Integer.parseInt(conditionid), specifications, features,
				Integer.parseInt(quantity));
		logger.info("Done update product");
		List<Products> prd = productDAO.getProductList();
		request.setAttribute("products", prd);
		return "ProductManage";
	}

	@RequestMapping(value = { "/CreateProductJsp.do" }, method = RequestMethod.GET)
	public String docreateproductjsp(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		List<Brand> brand = brandDAO.getBrandList();
		List<Deals> deal = dealsDAO.getDealsList();
		List<Condition> condition = conditionDAO.getConditionList();
		List<Productcatalog> cataloglist = productCatalogDAO
				.getProductCatalogList();
		request.setAttribute("brandlist", brand);
		request.setAttribute("deallist", deal);
		request.setAttribute("conditionlist", condition);
		request.setAttribute("cataloglist", cataloglist);
		return "CreateProduct";
	}

	@RequestMapping(value = { "/CreateProduct.do" }, method = RequestMethod.POST)
	public String doCreateProduct(
			@RequestParam(value = "file") List<MultipartFile> file,
			Model model, HttpServletRequest request,
			HttpServletResponse response) throws URISyntaxException {
		logger.info("Begin create product");
		String productname = request.getParameter("productname");
		String priceStr = request.getParameter("price");
		String model1 = request.getParameter("model");
		String warranty = request.getParameter("warranty");
		String tax = request.getParameter("tax");
		String description = request.getParameter("description");
		String dealid = request.getParameter("deal");
		String productcatalog = request.getParameter("productcatalog");
		String brandid = request.getParameter("brand");
		String specifications = request.getParameter("spec");
		String features = request.getParameter("features");
		String conditionid = request.getParameter("condition");
		String catalogid = request.getParameter("productcatalog");
		String quantity = request.getParameter("quantity");
		MultipartFile filenamemul = file.get(0);
		MultipartFile filename2mul = file.get(1);
		String filename = filenamemul.getOriginalFilename();
		String filename2 = filename2mul.getOriginalFilename();
		String imageURL1 = "";
		String imageURL2 = "";
		String filedes = request.getSession().getServletContext()
				.getRealPath("/images/")
				+ "/" + filename;
		String filedes2 = request.getSession().getServletContext()
				.getRealPath("/images/")
				+ "/" + filename2;
		File des = new File(filedes);
		File des2 = new File(filedes2);
		if (!des.exists()) {
			try {
				
				filenamemul.transferTo(des);

			} catch (Exception e) {
				logger.error("Error when tranfer file, this is it :",e);
				e.printStackTrace();
			}
		}
		if (!des2.exists()) {
			try {
				filename2mul.transferTo(des2);
			} catch (Exception e) {
				logger.error("Error when tranfer file, this is it :",e);
				e.printStackTrace();
			}
		}
		if (filename == "") {
			imageURL1 = "images/";
		} else
			imageURL1 = "images/" + filename;
		if (filename2 == "") {
			imageURL2 = "images/";
		} else
			imageURL2 = "images/" + filename2;
		if (dealid.equals(""))
			dealid = "-1";
		Productcatalog prdctlog = productCatalogDAO
				.getProductCatalog(productcatalog);
		Condition condition = conditionDAO.getCondition(conditionid);
		Brand brand = brandDAO.getBrand(brandid);
		Deals deal = dealsDAO.getDeals(dealid);
		Products prd = new Products(prdctlog, condition, deal, brand,
				productname, Float.parseFloat(priceStr), model1, description,
				Integer.parseInt(warranty), imageURL1, imageURL2,
				Float.parseFloat(tax), Integer.parseInt(quantity),
				specifications, features);
		logger.info("Product created");
		adminDAO.addProduct(prd);
		List<Products> prd1 = productDAO.getProductList();
		request.setAttribute("products", prd1);
		return "ProductManage";
	}
	
	// Product details
		@RequestMapping(value={"/ProductDetail.do"}, method = RequestMethod.GET) 
	    public String doProductDetail(Model model, HttpServletRequest request, HttpServletResponse response){ 
			 	
			String productid = request.getParameter("productid");
			Products product = productDAO.getProduct(productid);
			List<Comment> listcomment = commentDAO.getListCommentByProductid(productid);
			List<Products> listproductaccessories = productDAO.getProductList(product.getProductcatalog().getCatalogid().toString());
			request.setAttribute("listproductaccessories", listproductaccessories);
			request.setAttribute("listcomment", listcomment);
			request.setAttribute("product", product);
			String[] specifications = userDAO.listspecifications(product.getSpecifications());
			String[] features = userDAO.listspecifications(product.getFeatures());
			List<String> name = new ArrayList<String>();
			List<String> details = new ArrayList<String>();
			List<String> namefeatures = new ArrayList<String>();
			List<String> detailsfeatures = new ArrayList<String>();
			String temp;
			if(specifications.length > 0)
			{
			for(int i = 0; i < specifications.length; i++)
			{
				temp = specifications[i].split(":")[0];
				name.add(temp);
				temp = specifications[i].split(":")[1];
				details.add(temp);
			}
			}
			if(features.length > 0)
			{
			for(int i = 0; i < features.length; i++)
			{
				temp = features[i].split(":")[0];
				namefeatures.add(temp);
				temp = features[i].split(":")[1];
				detailsfeatures.add(temp);
			}
			}
			request.setAttribute("namefeatures", namefeatures);
			request.setAttribute("detailsfeatures",detailsfeatures);
			request.setAttribute("name", name);
			request.setAttribute("details", details);
	        return "ProductDetail"; 
	    }

	@RequestMapping(value = { "/CommentProduct.do" }, method = RequestMethod.POST)
	public String doCommentProduct(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		 
		// session = request.getSession();
		String productid = request.getParameter("productid");
		String rating = "0";
		if (request.getParameter("rating") != null)
			rating = request.getParameter("rating");
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		Products product = productDAO.getProduct(productid);
		String email;
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		email = auth.getName(); // get logged in username

		User user = userDAO.getUserInfo(email);
		Comment comment = new Comment(user, product, title, content,
				Integer.parseInt(rating));
		commentDAO.addComment(comment);
		List<Comment> listcomment = commentDAO
				.getListCommentByProductid(productid);
		int averagerating = 0;
		int count = 0, sum = 0;
		for (int i = 0; i < listcomment.size(); i++) {
			if (listcomment.get(i).getRating() > 0) {
				sum += listcomment.get(i).getRating();
				count++;
			}
		}
		if(count > 0)
			averagerating = sum / count;
		product.setRating(averagerating);
		productDAO.updateRating(averagerating, productid);
		List<Products> listproductaccessories = productDAO
				.getProductList(product.getProductcatalog().getCatalogid()
						.toString());
		request.setAttribute("listproductaccessories", listproductaccessories);
		request.setAttribute("listcomment", listcomment);
		request.setAttribute("product", product);
		
		
		String[] specifications = userDAO.listspecifications(product.getSpecifications());
		String[] features = userDAO.listspecifications(product.getFeatures());
		List<String> name = new ArrayList<String>();
		List<String> details = new ArrayList<String>();
		List<String> namefeatures = new ArrayList<String>();
		List<String> detailsfeatures = new ArrayList<String>();
		String temp;
		if(specifications.length > 0)
		{
		for(int i = 0; i < specifications.length; i++)
		{
			temp = specifications[i].split(":")[0];
			name.add(temp);
			temp = specifications[i].split(":")[1];
			details.add(temp);
		}
		}
		if(features.length > 0)
		{
		for(int i = 0; i < features.length; i++)
		{
			temp = features[i].split(":")[0];
			namefeatures.add(temp);
			temp = features[i].split(":")[1];
			detailsfeatures.add(temp);
		}
		}
		request.setAttribute("namefeatures", namefeatures);
		request.setAttribute("detailsfeatures",detailsfeatures);
		request.setAttribute("name", name);
		request.setAttribute("details", details);
		return "ProductDetail";
	}

	@RequestMapping(value = { "/Cart.do" }, method = RequestMethod.GET)
	public String doCart(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		 
		session = request.getSession();
		ArrayList<Products> listproductscart;
		if (session.getAttribute("listproductscart") == null) {
			listproductscart = new ArrayList<Products>();
			session.setAttribute("listproductscart", listproductscart);
		} else {
			listproductscart = (ArrayList<Products>) session
					.getAttribute("listproductscart");
		}
		String productid = request.getParameter("productid");
		if (productid != null) {
			boolean kq = false;
			for (int i = 0; i < listproductscart.size(); i++) {
				Products product = listproductscart.get(i);
				if (product.getProductid() == Integer.parseInt(productid)) {
					product.setQuantityforsell(product.getQuantityforsell() + 1);
					product.setQuantity(product.getQuantity() - 1);
					kq = true;
					break;
				}
			}
			if (kq == false) {
				Products pr = productDAO.getProduct(productid);
				pr.setQuantityforsell(1);
				listproductscart.add(pr);
			}
		}

		String update = request.getParameter("update.x");
		if (update != null) {
			String[] q = request.getParameterValues("quantityforsell");
			for (int i = 0; i < listproductscart.size(); i++) {
				int quantityforsell = Integer.parseInt(q[i]);
				listproductscart.get(i).setQuantityforsell(quantityforsell);
			}
		}

		// Lam check out
		String checkout = request.getParameter("checkout.x");
		if (checkout != null) {
			return "redirect:/CheckOut.do";
		}
		return "Cart";
	}

	@RequestMapping(value = { "/DeleteProductCart.do" }, method = RequestMethod.GET)
	public String doDeleteProductCart(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("Begin delete product cart");
		 
		ArrayList<Products> listproductscart;
		session = request.getSession();
		if (session.getAttribute("listproductscart") == null) {
			listproductscart = new ArrayList<Products>();
			session.setAttribute("listproductscart", listproductscart);
		} else {
			listproductscart = (ArrayList<Products>) session
					.getAttribute("listproductscart");
		}
		String productid = request.getParameter("productid");
		for (int i = 0; i < listproductscart.size(); i++) {
			if (listproductscart.get(i).getProductid() == Integer
					.parseInt(productid)) {
				listproductscart.remove(i);
				logger.info("Product cart deleted");
				break;
			}
		}
		return "Cart";
	}

	@RequestMapping(value = { "/WishList.do" }, method = RequestMethod.GET)
	public String doWishList(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		 
		session = request.getSession();
		List<Wishlist> wishlists = null;
		String email;
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		email = auth.getName(); // get logged in username

		// if (email == null){
		// email =(String) session.getAttribute("email");
		// }
		// else{
		// session.setAttribute("email",email);
		// }
		User user = userDAO.getUserInfo(email);
		if (session.getAttribute("wishlists") == null) {
			wishlists = wishListDAO.getWishlListByUser(user);
			session.setAttribute("wishlists", wishlists);
		} else {
			wishlists = (List<Wishlist>) session.getAttribute("wishlists");
		}
		boolean flagWishlist = false;
		if (request.getParameter("productid") != null) {
			String productid;
			productid = request.getParameter("productid");
			for (Wishlist wishlist : wishlists) {
				if (Integer.parseInt(productid) == wishlist.getProducts()
						.getProductid()) {
					flagWishlist = true;
					break;
				}
			}
			if (flagWishlist == false) {
				Products product = productDAO.getProduct(productid);
				Wishlist wishlist = new Wishlist(user, product);
				wishlists.add(wishlist);
				wishListDAO.addWishlist(wishlist);
				session.setAttribute("wishlists", wishlists);
			}

		}
		return "WishList";
	}

	@RequestMapping(value = { "/DeleteProductWishlist.do" }, method = RequestMethod.GET)
	public String doDeleteProductWishlist(Model model,
			HttpServletRequest request, HttpServletResponse response) {
		logger.info("Begin delete Product Wishlist");
		 
		List<Wishlist> wishlists;
		session = request.getSession();
		String email;
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		email = auth.getName(); // get logged in username

		// if (email == null){
		// email =(String) session.getAttribute("email");
		// }
		User user = userDAO.getUserInfo(email);
		String productid;
		productid = request.getParameter("productid");
		wishListDAO.removeWishListByProductid(productid);
		logger.info("Product Wishlist deleted");
		wishlists = wishListDAO.getWishlListByUser(user);
		session.setAttribute("wishlists", wishlists);
		return "WishList";
	}

	@RequestMapping(value = { "/CheckOut.do" }, method = RequestMethod.GET)
	public String doCheckOut(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("Begin checkout");
		 
		session = request.getSession();
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		String email = auth.getName(); // get logged in username
		ArrayList<Products> listproductscart = (ArrayList<Products>) session
				.getAttribute("listproductscart");
		float sumprice = 0;
		for (int i = 0; i < listproductscart.size(); i++) {
			Products pr = listproductscart.get(i);
			float price = pr.getPrice();// - (sp.getGiaBan() * sp.getGiamGia() /
										// 100);
			sumprice = sumprice + price
					* listproductscart.get(i).getQuantityforsell() + price
					* listproductscart.get(i).getQuantityforsell()
					* listproductscart.get(i).getTax() / 100;
			productDAO.updatetodatabase(listproductscart.get(i), listproductscart.get(i).getQuantityforsell());
		}
		
		Orders order = new Orders();
		// String maDonDatHang = donDatHangDAO.sinhMaDonDatHang(tenDangNhap, new
		// Date());
		// ddh.setMaDonDatHang(maDonDatHang);
		order.setOrderdate(new Date());
		order.setTotalmoney(sumprice);
		User user = userDAO.getUserInfo(email);
		order.setUser(user);
		order.setOrderstatus(orderStatusDAO.getOrderstatus(1));
		ordersDAO.addOrders(order);
		// donDatHangDAO.themDonDatHang(ddh);
		for (int i = 0; i < listproductscart.size(); i++) {
			Products pr = listproductscart.get(i);
			Orderdetail orde = new Orderdetail();
			orde.setOrders(order);
			// orde.setsetSoThuTu(i + 1);
			orde.setProducts(pr);
			// orde.set(sp.getGiaBan() - sp.getGiaBan() * sp.getGiamGia() /
			// 100);
			orde.setQuantity(pr.getQuantityforsell());
			orderDetailDAO.addOrderDetail(orde);
			// chiTietDonDatHangDAO.themChiTietDonDatHang(ct);
		}
		// Cap nhat so luong ton
		logger.info("Check out completed");
		session.removeAttribute("listproductscart");
		// String url = "LichSuMuaHang.do?action=xem&maDonDatHang=" +
		// maDonDatHang;
		// response.sendRedirect(url);
		// request.setAttribute("maDonDatHang", maDonDatHang);
		return "redirect:/OrderManage.do";
	}

	ArrayList<String> listfilter = new ArrayList<String>() {
		{
			add("this week");
			add("this month");
			add("this year");
		}
	};

	@RequestMapping(value = { "/OrderManage.do" }, method = RequestMethod.GET)
	public String doOrderManage(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		 
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		String email = auth.getName(); // get logged in username

		int filterorder = -1;
		if (request.getParameter("filterorder") != null) {
			filterorder = Integer.parseInt(request.getParameter("filterorder"));
		}

		List<Orders> listorders = ordersDAO.getListOrderByEmail(email,
				filterorder);
		request.setAttribute("filterorder", filterorder);
		request.setAttribute("listorders", listorders);
		request.setAttribute("listfilter", listfilter);
		return "OrderManage";
	}
	
	@RequestMapping(value = { "/UpdateOrderUser.do" }, method = RequestMethod.GET)
	public String UpdateOrderUser(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("Begin update order user");
		 
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		String email = auth.getName(); // get logged in username
		
		int filterorder = -1;
		if (request.getParameter("filterorder") != null) {
			filterorder = Integer.parseInt(request.getParameter("filterorder"));
		}

		List<Orders> listorders = ordersDAO.getListOrderByEmail(email,
				filterorder);
		request.setAttribute("filterorder", filterorder);
		request.setAttribute("listorders", listorders);
		request.setAttribute("listfilter", listfilter);
		logger.info("Update order user completed");
		return "OrderManage";
	}
	
	@RequestMapping(value = "/DownloadOrder.do", method = RequestMethod.GET)
	public ModelAndView doDownloadOrder(ModelAndView modelAndView, HttpServletRequest request,
			HttpServletResponse response) {
	Authentication auth = SecurityContextHolder.getContext()
			.getAuthentication();
	String email = auth.getName(); // get logged in username
	//JRDataSource datasource  = ordersDAO.getDataSource();//dataprovider.getDataSource();
	List<Orders> ordersList = ordersDAO.getDataSource(email);
    JRDataSource datasource = new JRBeanCollectionDataSource(ordersList);
	Map<String,Object> parameterMap = new HashMap<String,Object>();
	parameterMap.put("datasource", datasource);
	 
	// pdfReport is the View of our application
	// This is declared inside the /WEB-INF/jasper-views.xml
	modelAndView = new ModelAndView("pdfReport", parameterMap);
	 
	// Return the View and the Model combined
	return modelAndView;
	}
	
	@RequestMapping(value = "/DownloadOrderDetail.do", method = RequestMethod.GET)
	public ModelAndView doDownloadOrderDetail(ModelAndView modelAndView, HttpServletRequest request,
			HttpServletResponse response) {
		String orderid = request.getParameter("orderid");
		List<Orderdetail> listorderdetail = orderDetailDAO
				.getListOrderDetailByOrderid(orderid);
    JRDataSource datasource = new JRBeanCollectionDataSource(listorderdetail);
	Map<String,Object> parameterMap = new HashMap<String,Object>();
	parameterMap.put("datasource", datasource);
	 
	// pdfReport is the View of our application
	// This is declared inside the /WEB-INF/jasper-views.xml
	modelAndView = new ModelAndView("pdfReportDetail", parameterMap);
	 
	// Return the View and the Model combined
	return modelAndView;
	}
	
	@RequestMapping(value = { "/ViewOrderDetail.do" }, method = RequestMethod.GET)
	public String doViewOrderDetail(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		 

		String orderid = request.getParameter("orderid");
		List<Orderdetail> listorderdetail = orderDetailDAO
				.getListOrderDetailByOrderid(orderid);

		request.setAttribute("orderid", orderid);
		request.setAttribute("listorderdetail", listorderdetail);
		return "ViewOrderDetail";
	}

	@RequestMapping(value = { "/UserDetail.do" }, method = RequestMethod.GET)
	public String doLoadUserDetail(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		 
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		String email = auth.getName(); // get logged in username
		User user = userDAO.getUserInfo(email);
		request.setAttribute("user", user);
		return "UserDetail";
	}

	@RequestMapping(value = { "/UpdateUserDetail.do" }, method = RequestMethod.POST)
	public String doUserDetail(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("Begin update user details");
		 
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		String email = auth.getName(); // get logged in username
		String firstname;
		String lastname;
		String zipcode = "";
		String phonenumber = "";
		boolean returnResult1 = true;
		firstname = request.getParameter("firstname");
		lastname = request.getParameter("lastname");
		zipcode = request.getParameter("zipcode");
		phonenumber = request.getParameter("phonenumber");
		userDAO.updateUserDetail(email, firstname, lastname, zipcode, phonenumber);
		User user = userDAO.getUserInfo(email);
		request.setAttribute("user", user);
		String updatesuccess="Update Successfull!";
		request.setAttribute("updatesuccess", updatesuccess);
		logger.info("Update user details completed");
		return "UserDetail";
	}
	
	// Compare
//	@RequestMapping(value={"/Compare.do"}, method = RequestMethod.GET) 
//    public String docompare(Model model, HttpServletRequest request, HttpServletResponse response){ 
//		logger.info("Begin compare");
//		String[] listproducts = request.getParameterValues("compareproducts");
//		
//		if(listproducts.length ==4)
//		{
//		Products pd1 = productDAO.getProduct(listproducts[0]);
//		Products pd2 = productDAO.getProduct(listproducts[1]);
//		Products pd3 = productDAO.getProduct(listproducts[2]);
//		Products pd4 = productDAO.getProduct(listproducts[3]);
//		String compare =productDAO.Compare4(pd1.getSpecifications(), pd2.getSpecifications(), pd3.getSpecifications(), pd4.getSpecifications());
//		String[] list =compare.split("@");
//		List<String> row1 = new ArrayList<String>() ;
//		List<String> row2 =new ArrayList<String>();
//		List<String> row3 = new ArrayList<String>();
//		List<String> row4 = new ArrayList<String>();
//		List<String> row5 = new ArrayList<String>();
//		String temp;
//		for(int i = 0; i<list.length;i++)
//		{
//			temp = list[i].split(":")[0];
//			row1.add(temp);
//			temp = list[i].split(":")[1];
//			row2.add(temp);
//			temp = list[i].split(":")[2];
//			row3.add(temp);
//			temp = list[i].split(":")[3];
//			row4.add(temp);		
//			temp = list[i].split(":")[4];
//			row5.add(temp);
//		}
//		request.setAttribute("row1", row1);
//		request.setAttribute("row2", row2);
//		request.setAttribute("row3", row3);
//		request.setAttribute("row4", row4);
//		request.setAttribute("row5", row5);
//		request.setAttribute("pd1", pd1);
//		request.setAttribute("pd2", pd2);
//		request.setAttribute("pd3", pd3);
//		request.setAttribute("pd4", pd4);
//		request.setAttribute("pd1name", pd1.getProductname());
//		request.setAttribute("pd2name", pd2.getProductname());
//		request.setAttribute("pd3name", pd3.getProductname());
//		request.setAttribute("pd4name", pd4.getProductname());
//		request.setAttribute("img1", pd1.getImage1());
//		request.setAttribute("img2", pd2.getImage1());
//		request.setAttribute("img3", pd3.getImage1());
//		request.setAttribute("img4", pd4.getImage1());
//		request.setAttribute("sizeproduct", 4);
//		}
//		else if (listproducts.length == 3)
//		{
//			Products pd1 = productDAO.getProduct(listproducts[0]);
//			Products pd2 = productDAO.getProduct(listproducts[1]);
//			Products pd3 = productDAO.getProduct(listproducts[2]);
//			String compare =productDAO.Compare3(pd1.getSpecifications(), pd2.getSpecifications(), pd3.getSpecifications());
//			String[] list =compare.split("@");
//			List<String> row1 = new ArrayList<String>() ;
//			List<String> row2 =new ArrayList<String>();
//			List<String> row3 = new ArrayList<String>();
//			List<String> row4 = new ArrayList<String>();
//			String temp;
//			for(int i = 0; i<list.length;i++)
//			{
//				temp = list[i].split(":")[0];
//				row1.add(temp);
//				temp = list[i].split(":")[1];
//				row2.add(temp);
//				temp = list[i].split(":")[2];
//				row3.add(temp);
//				temp = list[i].split(":")[3];
//				row4.add(temp);		
//			}
//			request.setAttribute("row1", row1);
//			request.setAttribute("row2", row2);
//			request.setAttribute("row3", row3);
//			request.setAttribute("row4", row4);
//			request.setAttribute("pd1", pd1);
//			request.setAttribute("pd2", pd2);
//			request.setAttribute("pd3", pd3);
//			request.setAttribute("pd1name", pd1.getProductname());
//			request.setAttribute("pd2name", pd2.getProductname());
//			request.setAttribute("pd3name", pd3.getProductname());
//			request.setAttribute("img1", pd1.getImage1());
//			request.setAttribute("img2", pd2.getImage1());
//			request.setAttribute("img3", pd3.getImage1());
//			request.setAttribute("sizeproduct", 3);
//		}
//		else if(listproducts.length==2)
//		{
//			Products pd1 = productDAO.getProduct(listproducts[0]);
//			Products pd2 = productDAO.getProduct(listproducts[1]);
//			String compare =productDAO.Compare2(pd1.getSpecifications(), pd2.getSpecifications());
//			String[] list =compare.split("@");
//			List<String> row1 = new ArrayList<String>() ;
//			List<String> row2 =new ArrayList<String>();
//			List<String> row3 = new ArrayList<String>();
//			String temp;
//			for(int i = 0; i<list.length;i++)
//			{
//				temp = list[i].split(":")[0];
//				row1.add(temp);
//				temp = list[i].split(":")[1];
//				row2.add(temp);
//				temp = list[i].split(":")[2];
//				row3.add(temp);	
//			}
//			request.setAttribute("row1", row1);
//			request.setAttribute("row2", row2);
//			request.setAttribute("row3", row3);
//			request.setAttribute("pd1name", pd1.getProductname());
//			request.setAttribute("pd2name", pd2.getProductname());
//			request.setAttribute("sizeproduct", 2);
//			request.setAttribute("pd1", pd1);
//			request.setAttribute("pd2", pd2);
//			request.setAttribute("img1", pd1.getImage1());
//			request.setAttribute("img2", pd2.getImage1());
//		}
//		logger.info("Done compare");
//		return "Compare";
// 		
//	}
	 @RequestMapping(value={"/Compare.do"}, method = RequestMethod.GET) 
	 public String docompare(Model model, HttpServletRequest request, HttpServletResponse response){ 
	  logger.info("Begin compare");
	  //String[] listproducts = request.getParameterValues("compareproducts");
	  String[] listnameproducts = request.getParameterValues("compareproducts");
	  List<Products> listproducts = new ArrayList<Products>();
	  List<String> listproductspec = new ArrayList<String>(); 
	  
	  for(int i=0; i< listnameproducts.length; i++){
	   Products product = productDAO.getProduct(listnameproducts[i]);
	   listproductspec.add(product.getSpecifications());
	   listproducts.add(product);
	  }
	  String[] specs = listproductspec.toArray(new String[0]);
	  String compare = productDAO.CompareGeneral(specs);
	  String[] list = compare.split("@");
	  List<List<String>> row = new ArrayList<List<String>>();
	  for (int i=0;i<list.length;i++){
		  	String[] buf = list[i].split(":");
		   for(int j=0;j<buf.length;j++){
			   if(i==0)
				   row.add(new ArrayList<String>());
			   String temp;
			   temp = buf[j];
			   row.get(j).add(temp);
			   
		   }
	  }
	  for (int i=0;i<listproducts.size();i++){
	    request.setAttribute("pd"+(i+1), listproducts.get(i));
	    request.setAttribute("pd"+(i+1)+"name", listproducts.get(i).getProductname());
	    request.setAttribute("img"+(i+1), listproducts.get(i).getImage1());
	  }
	  for(int i=0;i<row.size();i++){
		  request.setAttribute("row" +(i+1), row.get(i));
	  }
	  request.setAttribute("sizeproduct", listproducts.size());
	  return "Compare";
	 }
	@RequestMapping(value = { "/UpdateUserPassword.do" }, method = RequestMethod.POST)
	public String doUpdateUserPassword(Model model, HttpServletRequest request,
			HttpServletResponse response) throws NoSuchAlgorithmException {
		logger.info("Begin update user password");
		 
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		String email = auth.getName(); // get logged in username
		User user = userDAO.getUserInfo(email);
		String passwordold;
		String passwordnew;
		String passwordnewre;
		String returnresult = " ";
		passwordold = request.getParameter("passwordold");
		//encrypt md5
		MessageDigest messageDigestOldPass = MessageDigest.getInstance("MD5");  
		messageDigestOldPass.update(passwordold.getBytes(),0, passwordold.length());  
		String hashedPassOldPass = new BigInteger(1,messageDigestOldPass.digest()).toString(16);  
		if (hashedPassOldPass.length() < 32) {
			hashedPassOldPass = "0" + hashedPassOldPass; 
		}
		request.setAttribute("user", user);
		if(hashedPassOldPass.equals(user.getPassword())){
			passwordnew = request.getParameter("passwordnew");
			passwordnewre = request.getParameter("passwordnewre");
			if(passwordnew.equals(passwordnewre)){
				//encrypt md5
				MessageDigest messageDigest = MessageDigest.getInstance("MD5");  
				messageDigest.update(passwordnew.getBytes(),0, passwordnew.length());  
				String hashedPass = new BigInteger(1,messageDigest.digest()).toString(16);  
				if (hashedPass.length() < 32) {
				   hashedPass = "0" + hashedPass; 
				}
				userDAO.updateUserPassword(email,hashedPass);
				
			}else{
				
				returnresult="Password doesn't match. Please try again!";
				request.setAttribute("returnresult", returnresult);
				return "UserDetail";
			}
		}
		else{
			returnresult="Incorrect Password. Please try again!";
			request.setAttribute("returnresult", returnresult);
			return "UserDetail";
		}
		
		String updatesuccess="Update Successfull!";
		request.setAttribute("updatesuccess", updatesuccess);
		logger.info("Done update password");
		return "UserDetail";
	}

}
